package com.eobard.config.security;

import com.eobard.entity.Permission;
import com.eobard.entity.User;
import com.eobard.service.PermissionService;
import com.eobard.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Eobard_Thawne
 * @version 1.0
 * @date 2022/8/6 -17:10
 */
@Component
public class CustomUserDetailsService implements UserDetailsService {

    @Resource
    private UserService userService;

    @Resource
    private PermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询用户信息
        User user = userService.findUserByUsername(username);
        if(null == user){
            throw new UsernameNotFoundException("用户名或密码错误！");
        }

        //获取当前用户的权限列表信息
        List<Permission> permissionList = permissionService.findPermissionByUserId(user.getId());
        //获取权限列表对应的角色代号,即sys:user:add
        List<String> codeList = permissionList.stream()
                .filter(item -> item != null)               //过滤权限列表为空的数据
                .map(Permission::getCode)                   //收集权限列表的角色代号
                .filter(item -> item != null)               //将收集的列表再次过滤为空的数据
                .collect(Collectors.toList());              //将最后的结果转为集合

        //设置用户的所有菜单列表
        user.setPermissionList(permissionList);

        //通过Spring Security的方法给当前用户授权:为当前用户增加对应的角色信息
        //需要将角色代号,即sys:user:add类型 转为数组形式
        String[] codeArray = codeList.toArray(new String[codeList.size()]);
        List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(codeArray);

        //设置用户的角色信息
        user.setAuthorities(authorityList);
        return user;
    }
}
